package com.fdway.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import org.apache.commons.io.FileUtils;



public class AdminAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private long tyid=1;
	private long id;
	private Content  con;
	private Contype  contype;
	private ArrayList<Contype> contyList;
	private ArrayList<Content> conList;
	private File back1; //�ļ�
	private String back1FileName; //�ļ����
	private String back1ContentType; //�ļ�����
	private String status;
	private Page page;
    private int currentPage=1;  //��ǰҳ
    private int everyPage=10;   //ÿҳ�ĸ���
    private String ran;
	

	public String getRan() {
		return ran;
	}

	public void setRan(String ran) {
		this.ran = ran;
	}

	@SuppressWarnings("unchecked")
	public String initAdmin(){
		ContypeDAO contydao=new ContypeDAO();
		Users user = (Users) request.getSession().getAttribute("user");
		if(user!=null&&user.getName().equals("admin")){
		    contyList=(ArrayList<Contype>) contydao.findAll();
		}else{
			long tyid=Long.parseLong(user.getBack1());
			contyList=(ArrayList<Contype>)contydao.findMyAll(tyid);
			this.tyid=tyid;
		}
		ContentDAO condao=new ContentDAO();
		ArrayList<Content> conls=(ArrayList<Content>) condao.findByTyid(tyid);
		contype=contydao.findById(tyid);
		Page p=new Page(); 
		p.setCurrentPage(currentPage);
		p.setEveryPage(everyPage);
		page = PageUtil.createPage(p,conls.size());
		conList=(ArrayList<Content>) condao.findByPage(tyid, page);
		
		return SUCCESS;
	}

	public String add() {
		if(con==null){
			return ERROR;
		}
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		con.setTime(format.format(date));
		ContentDAO condao = new ContentDAO();
		String realpath = request.getRealPath("/file");
		System.out.println("realpath: " + realpath);
		if (back1 != null) {
			/* �����1��Ч����ֻȡxxx.jpg��jpg */
			String extensionName = back1FileName.substring(back1FileName.lastIndexOf(".") + 1);
			//�����
			String newFileName=UUID.randomUUID().toString() + "." + extensionName;
			try {
				upFile(realpath,newFileName); //�ϴ��ļ�
				con.setBack1(realpath +"/" +newFileName);
				con.setBack2("1");
				con.setBack3(back1FileName);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		condao.start();
		condao.save(con);
		condao.commit();
		condao.close();
		return SUCCESS;
	}
	
	public void upFile(String realpath,String newFileName) throws IOException{
		File savefile = new File(new File(realpath), newFileName);
		if (!savefile.getParentFile().exists())
			savefile.getParentFile().mkdirs();
		try {
			FileUtils.copyFile(back1, savefile);
		}catch(IOException e){
			throw new IOException(e);
		}
	}
	
	public String downFile(){
		if(id==0){
			return ERROR;
		}
		ContentDAO condao=new ContentDAO();
		con=condao.findById(id);
		try {
			// path��ָ�����ص��ļ���·����
			File file = new File(con.getBack1());
			// ȡ���ļ���
			String filename = file.getName();
			// �������ʽ�����ļ���
			InputStream fis = new BufferedInputStream(new FileInputStream(con.getBack1()));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// ���response
			response.reset();
			// ����response��Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public String edit() throws Exception{
		
		String act=request.getParameter("act");
		ContentDAO condao=new ContentDAO();
		if("into".equals(act)){
			status="edit";
			ContypeDAO contydao=new ContypeDAO();
			Users user = (Users) request.getSession().getAttribute("user");
			if(user!=null&&user.getName().equals("admin")){
			    contyList=(ArrayList<Contype>) contydao.findAll();
			}else{
				long tyid=Long.parseLong(user.getBack1());
				contyList=(ArrayList<Contype>)contydao.findMyAll(tyid);
				this.tyid=tyid;
			}
			//contyList=(ArrayList<Contype>) contydao.findAll();
			con=condao.findById(id);
		}else if("edit".equals(act)){
			Date date=new Date();
		    SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    con.setTime(format.format(date));
			String realpath = request.getRealPath("/file");
			
			if (back1 != null) {
				/* �����1��Ч����ֻȡxxx.jpg��jpg */
				String extensionName = back1FileName.substring(back1FileName.lastIndexOf(".") + 1);
				//�����
				String newFileName=UUID.randomUUID().toString() + "." + extensionName;
				System.out.println("realpath: " + realpath+"/"+newFileName);
				try {
					upFile(realpath,newFileName); //�ϴ��ļ�
					con.setBack1(realpath +"/" +newFileName);
					con.setBack2("1");
					con.setBack3(back1FileName);
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//ActionContext.getContext().put("message", "�ļ��ϴ��ɹ�");
			}
			condao.start();
			condao.update(con);
			condao.commit();
			condao.close();
		}else{
			return null;
		}
		return SUCCESS;
	}
	
	public String del() throws Exception{
		ContentDAO condao=new ContentDAO();
		con=condao.findById(id);
		condao.start();
		condao.delete(con);
		condao.commit();
		condao.close();
		this.ran=new Random().toString();
		return SUCCESS;
	}
	
	public String delFile() throws Exception{
		ContentDAO condao=new ContentDAO();
		con=condao.findById(id);
		Utils.delFile(con.getBack1());
		con.setBack1("");
		con.setBack2("");
		con.setBack3("");
		condao.start();
		condao.update(con);
		condao.commit();
		condao.close();
		return SUCCESS;
	}

	public long getTyid() {
		return tyid;
	}

	public void setTyid(long tyid) {
		this.tyid = tyid;
	}

	public ArrayList<Contype> getContyList() {
		return contyList;
	}

	public void setContyList(ArrayList<Contype> contyList) {
		this.contyList = contyList;
	}

	public ArrayList<Content> getConList() {
		return conList;
	}

	public void setConList(ArrayList<Content> conList) {
		this.conList = conList;
	}

	public Content getCon() {
		return con;
	}

	public void setCon(Content con) {
		this.con = con;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public File getBack1() {
		return back1;
	}

	public void setBack1(File back1) {
		this.back1 = back1;
	}

	public String getBack1FileName() {
		return back1FileName;
	}

	public void setBack1FileName(String back1FileName) {
		this.back1FileName = back1FileName;
	}

	public String getBack1ContentType() {
		return back1ContentType;
	}

	public void setBack1ContentType(String back1ContentType) {
		this.back1ContentType = back1ContentType;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public Contype getContype() {
		return contype;
	}

	public void setContype(Contype contype) {
		this.contype = contype;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getEveryPage() {
		return everyPage;
	}

	public void setEveryPage(int everyPage) {
		this.everyPage = everyPage;
	}
	
	
	
   
}
